<template>
  <div class="order-page">
    <div class="order-controls">
      <el-input
          v-model="searchText"
          placeholder="搜索订单编号或类型喵~"
          @keyup.enter="searchOrders"
          class="search-input"
          clearable
      />
      <el-select v-model="filterType" placeholder="筛选订单类型" class="filter-select">
        <el-option label="全部" value="all" />
        <el-option label="拼车单" value="拼车单" />
        <el-option label="商城购物单" value="商城购物单" />
      </el-select>
    </div>

    <el-dialog v-model="showSearchDialog" title="搜索结果喵~" width="60%">
      <div v-if="searchResults.length > 0">
        <el-card
            v-for="order in searchResults"
            :key="order.orderId"
            shadow="hover"
            class="order-card"
            :class="order.statusClass"
            @click="jumpToOrder(order)"
            style="cursor: pointer"
        >
          <div class="order-header">
            <div class="order-status-icon" :title="order.status">
              <component :is="order.statusIcon" class="status-icon" />
            </div>
            <div><strong>订单编号：</strong>{{ order.orderId }}</div>
            <div><strong>订单类型：</strong>{{ order.orderType }}</div>
            <div><strong>创建时间：</strong>{{ formatDate(order.createTime) }}</div>
            <div><strong>金额：</strong>￥{{ order.totalAmount.toFixed(2) }}</div>
            <div><strong>状态：</strong>{{ order.status }}</div>
          </div>
        </el-card>
      </div>
      <div v-else>
        <p>没有找到相关订单喵~</p>
      </div>
    </el-dialog>
    <el-tabs v-model="activeTab" class="order-tabs">
      <el-tab-pane name="all">
        <template #label>
          所有订单
          <el-badge
              v-if="totalCount > 0"
              :value="totalCount"
              class="badge"
              style="margin-left: 6px;"
              :class="{'badge-gray': viewedTabs.all}"
          />
        </template>
      </el-tab-pane>
      <el-tab-pane name="initiated">
        <template #label>
          我发起的
          <el-badge
              v-if="initiatedCount > 0"
              :value="initiatedCount"
              class="badge"
              style="margin-left: 6px;"
              :class="{'badge-gray': viewedTabs.initiated}"
          />
        </template>
      </el-tab-pane>
      <el-tab-pane name="ongoing">
        <template #label>
          进行中
          <el-badge
              v-if="ongoingCount > 0"
              :value="ongoingCount"
              class="badge"
              style="margin-left: 6px;"
              :class="{'badge-gray': viewedTabs.ongoing}"
          />
        </template>
      </el-tab-pane>
      <el-tab-pane name="completed">
        <template #label>
          已完成
          <el-badge
              v-if="completedCount > 0"
              :value="completedCount"
              class="badge"
              style="margin-left: 6px;"
              :class="{'badge-gray': viewedTabs.completed}"
          />
        </template>
      </el-tab-pane>
    </el-tabs>

    <transition-group name="list-fade" tag="div" class="order-list" appear>
      <draggable
          v-model="filteredOrders"
          :disabled="activeTab !== 'all'"
          animation="200"
          item-key="orderId"
          @start="drag=true"
          @end="drag=false"
          class="draggable-wrapper"
      >
        <template #item="{ element: order }">
          <el-card
              :key="order.orderId"
              shadow="hover"
              class="order-card"
              :class="[
              { 'dragging-item': drag },
              order.statusClass
            ]"
          >
            <div class="order-header">
              <div class="order-status-icon" :title="order.status">
                <component :is="order.statusIcon" class="status-icon" />
              </div>
              <div><strong>订单编号：</strong>{{ order.orderId }}</div>
              <div><strong>订单类型：</strong>{{ order.orderType }}</div>
              <div><strong>创建时间：</strong>{{ formatDate(order.createTime) }}</div>
              <div><strong>金额：</strong>￥{{ order.totalAmount.toFixed(2) }}</div>
              <div><strong>状态：</strong> {{ order.status }}</div>
            </div>

            <div class="order-actions" v-if="order.status === '我发起的'">
              <el-button
                  size="small"
                  type="warning"
                  icon="el-icon-edit"
                  @click="modifyOrder(order)"
                  style="min-width: 80px;"
              >修改订单</el-button>

              <el-button
                  size="small"
                  type="danger"
                  icon="el-icon-close"
                  @click="cancelOrder(order)"
                  style="min-width: 80px;"
              >取消订单</el-button>
            </div>

            <div class="order-actions" v-if="order.status === '进行中'">
              <el-button
                  size="small"
                  type="success"
                  icon="el-icon-check"
                  @click="confirmComplete(order)"
                  style="min-width: 80px;"
              >完成订单</el-button>

              <el-button
                  size="small"
                  type="danger"
                  icon="el-icon-close"
                  @click="cancelOrder(order)"
                  style="min-width: 80px;"
              >取消订单</el-button>
            </div>

            <div v-if="order.status === '已完成'" class="review-area">
              <div v-if="order.review.submitted">
                <div class="submitted-review">
                  <div><strong>评分：</strong>
                    <el-rate v-model="order.review.rating" />
                  </div>
                  <div class="mt-2"><strong>评论内容：</strong></div>
                  <el-input
                      type="textarea"
                      v-model="order.review.comment"
                      rows="3"
                      maxlength="200"
                      show-word-limit
                  />
                  <el-button size="small" type="primary" class="mt-2" @click="submitReview(order)">更新评价</el-button>
                </div>
                <el-button
                    size="small"
                    type="danger"
                    icon="el-icon-delete"
                    @click="deleteOrder(order)"
                    style="min-width: 80px; margin-left: 8px;"
                >删除订单</el-button>
              </div>

              <div v-else>
                <el-rate v-model="order.review.rating" />
                <el-input
                    type="textarea"
                    v-model="order.review.comment"
                    placeholder="留下你的评价喵~"
                    rows="2"
                    show-word-limit
                    maxlength="200"
                />
                <el-button size="small" type="primary" class="mt-2" @click="submitReview(order)">提交评价</el-button>
                <el-button
                    size="small"
                    type="danger"
                    icon="el-icon-delete"
                    @click="deleteOrder(order)"
                    style="min-width: 80px; margin-left: 8px;"
                >删除订单</el-button>
              </div>
            </div>

          </el-card>
        </template>
      </draggable>
    </transition-group>

    <div class="return-home">
      <el-button type="primary" icon="el-icon-arrow-left" @click="goHome">返回主页</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import draggable from 'vuedraggable'

import { CheckCircleFilled, CloseCircleFilled, ClockCircleFilled } from '@element-plus/icons-vue'

const router = useRouter()
const activeTab = ref('all')
const drag = ref(false)

const allOrders = ref([
  {
    orderId: 101,
    orderType: '拼车单',
    createTime: '2025-05-10T12:30:00',
    totalAmount: 300.0,
    status: '我发起的',
    review: { rating: 0, comment: '' }
  },
  {
    orderId: 102,
    orderType: '商城购物单',
    createTime: '2025-05-12T08:45:00',
    totalAmount: 450.0,
    status: '进行中',
    review: { rating: 0, comment: '' }
  },
  {
    orderId: 103,
    orderType: '拼车单',
    createTime: '2025-05-08T14:00:00',
    totalAmount: 620.0,
    status: '已完成',
    review: { rating: 0, comment: '' }
  }
])

// 给每个订单动态添加状态相关类和图标
allOrders.value.forEach(order => {
  if (order.status === '我发起的') {
    order.statusClass = 'status-initiated'
    order.statusIcon = CloseCircleFilled
  } else if (order.status === '进行中') {
    order.statusClass = 'status-ongoing'
    order.statusIcon = ClockCircleFilled
  } else if (order.status === '已完成') {
    order.statusClass = 'status-completed'
    order.statusIcon = CheckCircleFilled
  } else {
    order.statusClass = ''
    order.statusIcon = null
  }
})

const initiatedCount = computed(() => allOrders.value.filter(o => o.status === '我发起的').length)
const ongoingCount = computed(() => allOrders.value.filter(o => o.status === '进行中').length)
const completedCount = computed(() => allOrders.value.filter(o => o.status === '已完成').length)
const totalCount = computed(() => allOrders.value.length)

const viewedTabs = ref({ all: false, initiated: false, ongoing: false, completed: false })

watch(activeTab, (newVal) => { viewedTabs.value[newVal] = true })

const filteredOrders = computed(() => {
  let list = allOrders.value
  if (filterType.value !== 'all') {
    list = list.filter(o => o.orderType === filterType.value)
  }
  if (activeTab.value === 'all') {
    list = [...list].sort((a, b) => {
      const statusOrder = { '我发起的': 1, '进行中': 2, '已完成': 3 }
      return statusOrder[a.status] - statusOrder[b.status] || new Date(b.createTime) - new Date(a.createTime)
    })
  } else {
    const statusMap = {
      initiated: '我发起的',
      ongoing: '进行中',
      completed: '已完成'
    }
    list = list.filter(o => o.status === statusMap[activeTab.value]).sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
  }
  return list
})
const formatDate = (str) => new Date(str).toLocaleString()

const goHome = () => router.push('/home')

const submitReview = (order) => {
  if (order.review.rating === 0 || !order.review.comment.trim()) {
    alert('请填写完整评价喵~')
    return
  }
  order.review.submitted = true
  alert(`评价已保存喵！订单号：${order.orderId}`)
  viewedTabs.value.completed = true
}


const cancelOrder = (order) => {
  if (confirm(`确认取消订单 ${order.orderId} 吗？`)) {
    allOrders.value = allOrders.value.filter(o => o.orderId !== order.orderId)
    alert(`订单 ${order.orderId} 已取消`)
  }
}

const deleteOrder = (order) => {
  if (confirm(`确认删除订单 ${order.orderId} 吗？删除后无法恢复！`)) {
    allOrders.value = allOrders.value.filter(o => o.orderId !== order.orderId)
    alert(`订单 ${order.orderId} 已删除`)
  }
}

const confirmComplete = (order) => {
  if (confirm(`订单 ${order.orderId} 确认完成了吗？`)) {
    const idx = allOrders.value.findIndex(o => o.orderId === order.orderId)
    if (idx !== -1) {
      allOrders.value[idx].status = '已完成'
      allOrders.value[idx].statusClass = 'status-completed'
      allOrders.value[idx].statusIcon = CheckCircleFilled
      alert(`订单 ${order.orderId} 已标记为完成`)
      viewedTabs.value.completed = false
    }
  }
}

const modifyOrder = (order) => {
  alert(`修改订单功能暂未实现，订单号：${order.orderId}`)
}
const searchText = ref('')
const showSearchDialog = ref(false)
const searchResults = ref([])
const filterType = ref('all')

const searchOrders = () => {
  const keyword = searchText.value.trim().toLowerCase()
  if (!keyword) return
  searchResults.value = allOrders.value.filter(o =>
      o.orderId.toString().includes(keyword) ||
      o.orderType.toLowerCase().includes(keyword)
  )
  showSearchDialog.value = true
}

const jumpToOrder = (order) => {
  activeTab.value = order.status === '我发起的'
      ? 'initiated'
      : order.status === '进行中'
          ? 'ongoing'
          : 'completed'
  showSearchDialog.value = false
  setTimeout(() => {
    const el = document.querySelector(`.order-card[data-id='${order.orderId}']`)
    if (el) el.scrollIntoView({ behavior: 'smooth' })
  }, 200)
}
</script>

<style scoped>
.order-page {
  padding: 20px;
  background: #f9f9f9;
  min-height: 100vh;
}
.order-tabs {
  margin-bottom: 20px;
}
.badge {
  background-color: #f56c6c;
  color: white;
  font-weight: bold;
  padding: 0 6px;
  border-radius: 12px;
}
.badge-gray {
  background-color: #c0c4cc;
}
.order-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}
.order-card {
  user-select: none;
  cursor: grab;
  transition: box-shadow 0.3s ease, transform 0.2s ease, border-color 0.3s ease;
  padding: 15px;
  border-left: 6px solid transparent;
  position: relative;
}
.dragging-item {
  cursor: grabbing !important;
  box-shadow: 0 0 15px #409eff;
  transform: scale(1.03);
  transition: transform 0.2s ease;
}

/* 不同订单状态配色和图标 */
.status-initiated {
  border-left-color: #f56c6c;
  background-color: #fff5f5;
}
.status-initiated:hover {
  background-color: #ffe6e6;
}
.status-ongoing {
  border-left-color: #e6a23c;
  background-color: #fffbea;
}
.status-ongoing:hover {
  background-color: #fff2cc;
}
.status-completed {
  border-left-color: #67c23a;
  background-color: #f0f9eb;
}
.status-completed:hover {
  background-color: #d3f9d8;
}

.order-header {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}
.order-header > div {
  flex: 1 1 150px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.order-status-icon {
  margin-right: 12px;
  font-size: 24px;
  color: inherit;
  display: flex;
  align-items: center;
}
.status-initiated .order-status-icon {
  color: #f56c6c;
}
.status-ongoing .order-status-icon {
  color: #e6a23c;
}
.status-completed .order-status-icon {
  color: #67c23a;
}

.order-actions {
  margin-top: 15px;
  display: flex;
  gap: 12px;
}

.review-area {
  margin-top: 15px;
}
.return-home {
  margin-top: 40px;
  text-align: center;
}

/* transition-group 动画 */
.list-fade-enter-active,
.list-fade-leave-active {
  transition: all 0.3s ease;
}
.list-fade-enter-from,
.list-fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}
.order-controls {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 20px;
}
.search-input {
  flex: 2;
  min-width: 200px;
}
.filter-select {
  flex: 1;
  min-width: 120px;
}
.submitted-review {
  background: #fefefe;
  border: 1px solid #ebeef5;
  padding: 10px;
  border-radius: 6px;
}

</style>
